<template>
  <div class="app-container">
    <el-form :inline="true" ref="ruleForm">
      <el-form-item label="代理账号：">
        <el-input
          v-model.trim="searchValue"
          @keyup.enter.native="onSearch"
        />
      </el-form-item>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="onSearch"
        :loading="loading"
      >
        搜索
      </el-button>
    </el-form>
    <Tree
      v-if="!loading"
      :props="treeProps"
      :load="loadNode"
      lazy
      :expand-on-click-node="false"
      node-key="uid"
      :default-expanded-keys="defaultKeyList"
    >
      <div
        class="custom-tree-node" slot-scope="{ node, data }"
      >
        <div :class="{'deepBgColor':data.name.toLowerCase()==searchName.toLowerCase()}"></div>
        <span
          class="tree-item-text"
          :style="formatCommStyle(data)"
          @click="openDialog({props: data, dialogName: dialogType.agenTreeDeta})"
        >
          {{ data.name }}({{data.size}})
        </span>
      </div>
    </Tree>
    <AgencyTreeDetailsDialog
      v-if="dialogName === dialogType.agenTreeDeta"
      v-model="dialogVisible"
      :id="dialogProps.uid"
      :rowData="dialogProps"
      @submit="submitFinished"
    />
    <BackToTop />
  </div>
</template>

<script>

// utils
import { delay, formatCommMode, getTreePathList } from '@/utils/base';

// components
import Tree from '@/components/Tree/Tree';
import BackToTop from '@/components/BackToTop/index';
import AgencyTreeDetailsDialog from './agencyTreeDetailsDialog';

// mixins
import { grid, dialog } from '@/build';

// service
import { getProxyTreeSearch, getProxyTreeChild } from '@/services/api/agency';

const dialogType = {
  agenTreeDeta: 'agency-tree-details-dialog',
};

export default {
  name: 'agencyTree',
  mixins: [grid, dialog],
  components: {
    BackToTop,
    AgencyTreeDetailsDialog,
    Tree,
  },
  data() {
    return {
      loading: false,
      searchValue: '',
      searchName: '',
      treeProps: {
        isLeaf: 'leaf',
      },
      treeData: {},
      defaultKeyList: [],
      dialogName: null,
      dialogType,
    };
  },
  methods: {
    formatCommStyle(data) {
      const { style } = formatCommMode(data.mode);
      return {
        ...style,
        ...this.formatCurrPathStyle(data.uid),
      };
    },
    formatCurrPathStyle(uid = '') {
      const { defaultKeyList, searchValue } = this;
      if (!(defaultKeyList.includes(uid) && searchValue && uid && defaultKeyList.length > 1)) {
        return {};
      }
      return {
        border: '2px solid rgb(243, 103, 74)',
      };
    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        if (!Object.keys(this.treeData).length) return resolve([]);
        return resolve(
          [this.treeData],
        );
      }
      if (node.data.childrenList) {
        const data = node.data.childrenList.map(value => this.formatData(value));
        resolve(data);
        return;
      }
      try {
        const [status, result] = await getProxyTreeChild(node.data);
        if (!status) throw new Error(result.message);
        const data = result.children.map(value => this.formatData(value));
        resolve(data);
      } catch (e) {
        this.$message({
          message: `获取数据失败.${e.message || ''}`,
          type: 'error',
        });
      }
    },
    initDefaultKeyList(data) {
      if (!(data && Object.keys(data).length)) return;
      const { uid, children = [] } = data;

      let searchPathList = [uid];
      if (this.searchValue) {
        const result = getTreePathList(children, this.searchValue, { returnIndex: true });
        const resUidList = result.map(v => v.uid);
        const resIndexList = result.map(v => v.index);
        this.handleScrollTop(resIndexList);
        searchPathList = [
          ...searchPathList,
          ...resUidList,
        ];
      }
      this.defaultKeyList = searchPathList;
    },
    async handleScrollTop(indexList) {
      const initHeight = 26;
      const top = indexList.reduce((total, currValue) => total + ((currValue + 1) * initHeight), initHeight);
      if (!window.scrollTo) return;
      await delay(500);
      window.scrollTo({
        top,
        behavior: 'smooth',
      });
    },
    formatData(data) {
      if (!data) return {};
      return ({
        ...data,
        leaf: data.size === 0,
        children: null,
        childrenList: data.children,
      });
    },
    onSearch() {
      this.treeData = {};
      this.searchName = this.searchValue;
      this.getAll();
    },
  },
  mounted() {
    this.bindGet(getProxyTreeSearch, 'treeData', {
      action: 'getGrid',
      sendingData: 'filters',
      format: (data) => {
        this.initDefaultKeyList(data);
        return this.formatData(data);
      },
      beforeSend: () => ({
        userName: this.searchValue,
      }),
    });
    this.getAll();
  },
};
</script>

<style lang="scss" scoped>
  .app-container /deep/[tabindex='0']>div:first-child{
    background-color: transparent!important;
  }
  .app-container /deep/.el-icon-caret-right{
    z-index: 1;
  }
  .app-container /deep/.is-expanded>div:first-child{
    background-color: #f5f7fa;
  }
  .app-container /deep/ .el-tree-node__content{
    position: relative;
    width: 100%;
  }
  .app-container /deep/ .el-icon-loading{
    z-index: 1;
  }
  .deepBgColor{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 26px;
    background-color: #eaeaea;
  }
  .custom-tree-node{
    width: 100%;
  }
  .tree-item-text {
    position: relative;
    padding: 2px 4px;
    border-radius: 4px;
    color: #ffffff;
  }
</style>
